using System;
using System.Diagnostics;
using System.IO;

public class DetectionService
{
    /// <summary>
    /// 执行YOLOv5目标检测脚本并返回结果图片路径
    /// </summary>
    /// <param name="projectPath">项目根路径</param>
    /// <param name="pythonPath">Python解释器路径</param>
    /// <param name="detectScriptPath">detect.py脚本路径</param>
    /// <param name="sourceImagePath">待检测图片路径</param>
    /// <param name="weightsPath">模型权重文件路径</param>
    /// <param name="confThreshold">置信度阈值</param>
    /// <param name="iouThreshold">IOU阈值</param>
    /// <param name="outputDir">输出目录</param>
    /// <param name="resultName">结果名称(文件夹名)</param>
    /// <returns>检测结果图片的完整路径</returns>
    public string RunDetection(
        string projectPath,
        string pythonPath,
        string detectScriptPath,
        string sourceImagePath,
        string weightsPath,
        double confThreshold,
        double iouThreshold,
        string outputDir,
        string resultName)
    {
        // 构建输出路径
        string resultPath = Path.Combine(outputDir, resultName);

        //移除之前的检测结果
        if (Directory.Exists(resultPath))
        {
            Directory.Delete(resultPath, true);
        }
        // 确保输出目录存在（yolo检测时会自动创建）
        //Directory.CreateDirectory(resultPath);

        // 构建命令参数
        string arguments = $"\"{detectScriptPath}\" " +
                          $"--source \"{sourceImagePath}\" " +
                          $"--weights \"{weightsPath}\" " +
                          $"--conf-thres {confThreshold} " +
                          $"--iou-thres {iouThreshold} " +
                          $"--name \"{resultPath}\"";

        // 配置进程启动信息
        ProcessStartInfo startInfo = new ProcessStartInfo
        {
            FileName = pythonPath,
            Arguments = arguments,
            WorkingDirectory = projectPath,
            UseShellExecute = false,
            CreateNoWindow = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };

        // 启动进程执行检测
        using (Process process = Process.Start(startInfo))
        {
            // 等待进程执行完成
            process.WaitForExit();
            
            // 可以获取输出和错误信息用于调试
            string output = process.StandardOutput.ReadToEnd();
            string error = process.StandardError.ReadToEnd();
            Console.WriteLine($"输出: {output}");
            Console.WriteLine($"错误: {error}");
            // 检查是否执行成功
            if (process.ExitCode != 0)
            {
                throw new Exception($"检测脚本执行失败: {error}");
            }
        }

        // 默认YOLOv5会在结果目录下生成exp或指定名称的子目录
        // 假设检测结果图片与原图片同名
        string detectedImagePath = Path.Combine(resultPath, Path.GetFileName(sourceImagePath));
        
        // 检查结果文件是否存在
        if (!File.Exists(detectedImagePath))
        {
            // 如果没有找到同名文件，尝试查找目录中的第一个图片文件
            string[] imageFiles = Directory.GetFiles(resultPath);
            if (imageFiles.Length > 0)
            {
                detectedImagePath = imageFiles[0];
            }
            else
            {
                throw new FileNotFoundException("未找到检测结果图片文件");
            }
        }

        return detectedImagePath;
    }
}

